package io.github.houhanzhi.hhregistry.cluster;

import io.github.houhanzhi.hhregistry.http.HttpInvoker;
import io.github.houhanzhi.hhregistry.service.HHRegistryService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * check health for servers
 */
@Slf4j
public class ServerHealth {
    
    final Cluster cluster;

    public ServerHealth(Cluster cluster) {
        this.cluster = cluster;
    }

    final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

    // 心跳间隔5s
    long interval = 5_000;
    public void checkServerHealth() {
        // 探活
        executorService.scheduleAtFixedRate(() -> {
            try {
                // 更新服务器状态
                updateServers();
                // 选举
                doElect();
                // 同步快照
                syncSnapshotFromLeader();

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }, 0, interval, TimeUnit.MILLISECONDS);
    }

    private void doElect() {
        new Election().electLeader(cluster.getServers());
    }

    private void syncSnapshotFromLeader() {

        Server self = cluster.self();
        Server leader = cluster.leader();
        
        if (!self.isLeader() && self.getVersion() < leader.getVersion()) {
            log.debug(" ===> leader version:{}", leader.getVersion() + ", my version:{}", self.getVersion());
            log.debug(" ===> sync snapshot from leader:{}", leader);
            Snapshort snapshort = HttpInvoker.httpGet(leader.getUrl() + "/snapshot", Snapshort.class);
            log.debug(" ===> sync snapshot:{}", snapshort);
            // 恢复快照
            HHRegistryService.restore(snapshort);
        }
    }

    

    private void updateServers() {
        // 改成并行处理探活，提升性能
        cluster.getServers().stream().parallel().forEach(server -> {
            try {
                // 忽略自己
                if (server.equals(cluster.MYSELF)) {
                    return;
                }
                Server serverInfo = HttpInvoker.httpGet(server.getUrl() + "/info", Server.class);
                log.debug(" ===> health check success for:{} " , serverInfo);
                if (serverInfo != null) {
                    server.setStatus(true);
                    server.setLeader(serverInfo.isLeader());
                    server.setVersion(serverInfo.getVersion());
                }
            } catch (Exception ex) {
                // 宕机等访问不到原因
                log.debug(" ===> health check failed for:{}  " , server);
                server.setStatus(false);
                server.setLeader(false);
            }

        });
    }


    
}
